import React, { useState } from 'react';
import { usePagination } from 'ahooks';
import { Link } from 'umi';
import UniversalPagination from '@/components/UniversalPagination';
import { Button, message, Input, Modal, Space, Card, Image, Typography, Tag } from 'antd';
import CreateModalForm from './components/CreateModalForm';
import UpdateModalForm from './components/UpdateModalForm';
import { GridContent } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import tableStyle from '@/styles/publicTable.less';
import CategorySelect from '@/components/CategorySelect';
const { Text } = Typography;

import { getGoodsList, deleteGoods } from './service';
const { confirm } = Modal;
interface TableListProps extends FormComponentProps {}

const GoodsList: React.FC<TableListProps> = () => {
  const [refreshCount, setRefreshCount] = useState(0);
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    category_id: '',
  });
  /**
   *  删除节点
   * @param id
   */
  const handleDelete = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      const res = await deleteGoods(id);
      hide();
      if (res?.success) {
        message.success('删除成功');
      } else {
      }

      return true;
    } catch (error) {
      hide();
      message.error('删除失败');
      return false;
    }
  };

  /**
   *  获取数据列表
   * @param selectedRows
   */
  const fetchList = async (params: {
    page: number;
    pageSize: number;
    keyword: string;
    category_id: string;
  }) => {
    try {
      const res = await getGoodsList({
        ...params,
      });
      if (res.success) {
        return {
          total: res.data.totalNum,
          list: res.data.list,
        };
      } else {
        return { total: 0, list: [] };
      }
    } catch (error) {
      return { total: 0, list: [] };
    }
  };

  const columns: ProColumns[] = [
    {
      title: '商品名',
      dataIndex: 'title',
      hideInSearch: true,
      // align: 'center',
      className: tableStyle.firstColumnPadding,
      width: '90px',
      render: (_, record) => {
        return <Link to={`/goods/detail/${record.id}`}>{record.title}</Link>;
      },
    },
    {
      title: '分类',
      dataIndex: 'category',
      hideInSearch: true,
      width: '90px',
      align: 'center',
      render: (_) => <span> {_.name}</span>,
    },
    {
      title: '商品主图',
      dataIndex: 'image_url',
      hideInSearch: true,
      width: '120px',
      align: 'center',
      render: (_) => {
        return <Image src={_ ? _ : ''} />;
      },
    },
    {
      title: '小标题',
      dataIndex: 'sub_title',
      hideInSearch: true,
      width: '120px',
      align: 'center',
    },
    {
      title: '详细描述',
      dataIndex: 'desc',
      width: '130px',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '折扣前价格',
      dataIndex: 'original_price',
      width: '90px',
      align: 'center',
      hideInSearch: true,
      render: (_) => {
        return _ ? (
          <Text delete type="secondary">
            {_} ¥
          </Text>
        ) : (
          ''
        );
      },
    },
    {
      title: '折扣后价格',
      dataIndex: 'current_price',
      width: '90px',
      align: 'center',
      hideInSearch: true,
      render: (_) => {
        return _ ? <span style={{ color: '#108ee9' }}>{_} ¥</span> : '';
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
      width: '90px',
      align: 'center',
      hideInSearch: true,
      render: (_) => <span style={{ color: '#ff5500' }}>{_}</span>,
    },
    {
      title: '销量',
      dataIndex: 'sales_volume',
      width: '90px',
      align: 'center',
      hideInSearch: true,
      render: (_) => <span style={{ color: '#87d168' }}>{_}</span>,
    },
    {
      title: '状态',
      dataIndex: 'is_onShelf',
      width: '90px',
      align: 'center',
      hideInSearch: true,
      render: (_) => {
        return _ ? <Tag color="#87d068">已上架</Tag> : <Tag color="#f50">已下架</Tag>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: '120px',
      align: 'center',
      render: (_, row) => (
        <Space direction="horizontal" style={{ width: '100%' }}>
          <UpdateModalForm formVals={row} setRefreshCount={setRefreshCount} />
          <Button
            type="default"
            size="small"
            onClick={() => {
              confirm({
                title: '是否删除商品？',
                content: (
                  <div>
                    是否删除商品<b>{`"${row.title}"`}</b>？
                  </div>
                ),
                okType: 'danger',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleDelete(row.id);
                  if (success) {
                    setRefreshCount(refreshCount + 1);
                  }
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  const { data, loading, pagination } = usePagination(
    ({ current, pageSize }) => {
      return fetchList({
        page: current,
        pageSize,
        keyword: searchParams.keyword,
        category_id: searchParams.category_id,
      });
    },
    {
      refreshDeps: [searchParams, refreshCount],
    },
  );
  return (
    <GridContent>
      <Card bodyStyle={{ padding: '32px 24px' }}>
        <Space direction="vertical" size={32} style={{ width: '100%' }}>
          <Space direction="horizontal" size={32} style={{ width: '100%' }}>
            <Input.Search
              style={{ width: 300 }}
              size="large"
              allowClear
              placeholder="输入关键词搜索"
              onSearch={(val) => {
                setSearchParams({
                  ...searchParams,
                  keyword: val,
                });
              }}
            />
            <CategorySelect
              onChange={(id) => {
                setSearchParams({ ...searchParams, category_id: id ? id : '' });
              }}
            />
          </Space>
          <Card
            title="商品管理"
            extra={<CreateModalForm setRefreshCount={setRefreshCount} />}
            bodyStyle={{ padding: 0 }}
          >
            <ProTable
              className={tableStyle.proTableFirstColumnPadding}
              columns={columns}
              loading={loading}
              dataSource={data?.list}
              rowKey="id"
              options={false}
              search={false}
              pagination={false}
            />
            <UniversalPagination pagination={pagination} total={data?.total} />
          </Card>
        </Space>
      </Card>
    </GridContent>
  );
};

export default GoodsList;
